<template>
    <!-- 自主开方页面 -->
    <section class="video-page subsitute-page">

        <!-- ------------------ 提示音 ------------------ -->
        <audio id="dingding">
            <source src="@/assets/music/dingding.mp3" type="audio/mpeg">
        </audio>
        <el-button @click.native="tipMusicBtn" ref="upload" v-show="false">播放</el-button>


        <div class="l-flex flex-row-between page-frame">
            <!-- ------------------ 患者模块 ------------------ -->
            <div class="l-flex-1">
                <div class="frame__box frame__patient">
                    <div class="frame__head l-flex flex-row-between">
                        <div class="l-flex-1 head__title">
                            <img class="head__icon" src="@/assets/img/icon_case.png" alt="">
                            <span>问诊病例</span>
                            <el-link class="frame-icon" :underline="false" icon="el-icon-edit-outline" @click="onShowDialog('updatePatient')">编辑就诊人</el-link>
                        </div>
                        <!-- --------- 特殊情况提示 --------- -->
                        <div v-show="patientInfo.isChildOption" class="l-flex-1 head__tips">
                            {{ `患者为${patientInfo.isChildOption}，请谨慎用药` }}
                        </div>
                    </div>
                    <div class="frame__body">
                        <!-- --------- 患者资料 --------- -->
                        <div class="patient-info x-desc has-flex s-column--3">
                            <div v-for="(o, i) in patientInfoField" :class="['desc__item', o.column ? `s-column--${o.column}` : '']" :key="i">
                                <div class="desc__label">{{ o.label }}：</div>
                                <!-- 性别 -->
                                <div v-if="o.slot == 'patientSex'" class="desc__value">
                                    {{ $util.filterByIds(patientInfo[o.slot], $dict.sexIds)}}
                                </div>
                                <!-- 身高/体重 -->
                                <div v-else-if="o.slot == 'patientWeight'" class="desc__value">
                                    <span>{{ patientInfo.patientHeight }}</span>
                                    /
                                    <span>{{ patientInfo.patientWeight }}</span>
                                </div>
                                <!-- 婚姻状态 -->
                                <div v-else-if="o.slot == 'isMarried'" class="desc__value">
                                    {{ $util.filterByIds(patientInfo[o.slot], $dict.marriedIds) }}
                                </div>
                                <!-- 地址 -->
                                <div v-else-if="o.slot == 'autonomousAddress'" class="desc__value">
                                    {{ patientInfo.addressCity || '' }} {{ patientInfo.autonomousAddress  || '' }}
                                </div>

                                <!-- 过敏史 -->
                                <div v-else-if="o.slot == 'isDrugAllergy'" class="desc__value">
                                    {{ patientInfo[o.slot] == 1 ? patientInfo.patientAllergyDetails : '无' }}
                                    <el-link class="frame-icon" :underline="false" icon="el-icon-edit" @click="openDialog('allergyHistoryDialog')"></el-link>
                                </div>
                                <!-- 付费类型 -->
                                <div v-else-if="o.slot == 'paymentMethod'" class="desc__value">
                                    {{ $util.filterByIds(patientInfo[o.slot], $dict.paymentMethodIds) }}
                                    <!-- <el-link class="frame-icon" :underline="false" icon="el-icon-edit" @click="openDialog('payment')"></el-link> -->
                                </div>
                                <!-- 主诉 -->
                                <div v-else-if="o.slot == 'mainSuit'" class="desc__value">
                                    <span>{{ patientInfo[o.slot] }}</span>
                                    <el-link class="frame-icon" :underline="false" icon="el-icon-edit" @click="openDialog('chiefComplaintDialog','1')"></el-link>
                                </div>
                                <!-- 现病史 -->
                                <div v-else-if="o.slot == 'presentIllness'" class="desc__value">
                                    <span>{{ patientInfo[o.slot] }}</span>
                                    <el-link class="frame-icon" :underline="false" icon="el-icon-edit" @click="openDialog('chiefComplaintDialog','2')"></el-link>
                                </div>
                                <!-- 既往史 -->
                                <div v-else-if="o.slot == 'historyPresentIllness'" class="desc__value">
                                    <span>{{ patientInfo[o.slot] }}</span>
                                    <el-link class="frame-icon" :underline="false" icon="el-icon-edit" @click="openDialog('chiefComplaintDialog','3')"></el-link>
                                </div>
                                <!-- 诊断 -->
                                <div v-else-if="o.slot == 'diagnosisArray'" class="desc__value">
                                    <span>{{ patientInfo.diagnosisDescribe }}</span>
                                    <el-link class="frame-icon" :underline="false" icon="el-icon-edit" @click="openDiagnosisDialog(patientInfo.diagnosisArray)"></el-link>
                                </div>
                                <!-- 处方 -->
                                <div v-else-if="o.slot == 'prescriptionList'" class="desc__value">
                                    <el-button v-for="(item,index) in patientInfo.prescriptionList" :key="index" size="mini" type="primary" plain @click="getEstablishPdf(item.id,4)">
                                        {{item.prescriptionNo}}
                                    </el-button>
                                </div>
                                <div v-else class="desc__value">{{ patientInfo[o.prop] }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- ------------------ 操作模块 ------------------ -->
                <div class="frame__box frame__handles">
                    <div class="frame__body">
                        <div class="chat__handle">
                            <div class="handle__item" @click="openDialog('caseHistory')">
                                <img class="item__icon" src="@/assets/img/icon_medical_record.png" alt="">
                                <p class="item__txt">查询病历</p>
                            </div>
                            <div class="handle__item" @click="openDialog('westernMedicineDialog')">
                                <img class="item__icon" src="@/assets/img/icon_western_medicine.png" alt="">
                                <p class="item__txt">西药处方</p>
                            </div>
                            <div class="handle__item" @click="openDialog('chineseMedicineDialog')">
                                <img class="item__icon" src="@/assets/img/icon_traditional_chinese_medicine.png" alt="">
                                <p class="item__txt">中药处方</p>
                            </div>
                            <div class="handle__item" @click="openDialog('finishDataDialog')">
                                <img class="item__icon" src="@/assets/img/icon_end.png" alt="">
                                <p class="item__txt">结束问诊</p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- ------------------ 历史处方模块 ------------------ -->
            <div class="frame__box frame__history">
                <div class="frame__head l-flex flex-row-between">
                    <div class="l-flex-1 head__title">
                        <img class="head__icon" src="@/assets/img/icon_case.png" alt="">
                        <span>历史处方</span>
                    </div>
                </div>
                <div class="frame__body">
                    <!-- --------- 搜索处方 --------- -->
                    <el-input class="history__search" placeholder="请输入就诊人姓名、身份证、手机号" v-model="historySearch" size="small" @keyup.enter.native="getHistoryList" clearable @clear="getHistoryList">
                        <el-button slot="append" icon="el-icon-search" @click="getHistoryList"></el-button>
                    </el-input>

                    <ul class="history__list">
                        <li class="history__item" v-for="(o, i) in historyList" :key="i">
                            <div class="item__row">{{ o.patientName }}（{{o.patientIdcard}}）</div>
                            <div class="item__row">
                                <span class="row__label">电话：</span>
                                {{ o.patientPhone }}
                            </div>
                            <div class="item__row">
                                <span class="row__label">上次问诊：</span>
                                {{ o.inquiryTime }}
                            </div>
                            <div class="item__row">
                                <span class="row__label">处方：</span>
                                <template v-if="o.prescriptionInquiryListVOList && o.prescriptionInquiryListVOList.length > 0">
                                    <el-link v-for="(c, cIndex) in o.prescriptionInquiryListVOList" class="o-link" :key="cIndex" type="primary" @click="getEstablishPdf(c.prescriptionId, 4)"> {{ c.prescriptionNo }}</el-link>
                                </template>
                                <template v-else>暂无</template>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>


        <!-- ------------------ 查看PDF ------------------ -->
        <pdf-dialog ref="pdfDialog" :has-save="false"></pdf-dialog>


        <!-- ------------------ 过敏史 ------------------ -->
        <el-dialog class="dialog-frame" width="600" title="药物过敏史" :visible.sync="allergyHistoryDialog" @close="closeDialog('allergyHistoryDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div>
                <el-radio v-model="isAllergy" label="1">有过敏史</el-radio>
                <el-radio v-model="isAllergy" label="2">无过敏史</el-radio>
            </div>
            <div v-if="isAllergy == '1'" style="margin-top:20px">
                <el-input v-model="isAllergyInput" style="resize:none;" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"></el-input>
            </div>
            <div slot="footer" class="dialog-btn">
                <el-button size="small" @click="closeDialog('allergyHistoryDialog')">取 消</el-button>
                <el-button type="primary" size="small" :loading="allergyLoading" @click="updateAllergyHistory">确 定</el-button>
            </div>
        </el-dialog>


        <!-- ------------------ 主诉/现病史/既往史 ------------------ -->
        <el-dialog class="dialog-frame" width="600" :visible.sync="chiefComplaintDialog" @close="closeDialog('chiefComplaintDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size" style="position: relative;">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>填写主诉</span>
            </div>
            <el-tabs v-model="chiefComplaintName" @tab-click="handleChiefClick">
                <el-tab-pane label="主诉" name="1">
                    <el-input type="textarea" style="resize:none;" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入主诉" v-model="chiefDialog.chiefInput">
                    </el-input>
                </el-tab-pane>
                <el-tab-pane label="现病史" name="2">
                    <el-input type="textarea" style="resize:none;" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入现病史" v-model="chiefDialog.nowInput">
                    </el-input>
                </el-tab-pane>
                <el-tab-pane label="既往史" name="3">
                    <el-input type="textarea" style="resize:none;" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入既往史" v-model="chiefDialog.pastInput">
                    </el-input>
                </el-tab-pane>
            </el-tabs>
            <div style="position: absolute;top: 67px;right: 30px;">
                <el-button size="small" @click="clearChief">清空{{chiefComplaintName == '1' ? '主诉':chiefComplaintName == '2' ? '现病史' : '既往史'}}</el-button>
                <el-button type="primary" size="small" @click="openDialog('chiefModelDialog')"><i class="el-icon-plus"></i> 新增模板</el-button>
            </div>
            <div class="content-title" style="position: relative;">
                <span>常用模板</span>
                <div style="position: absolute;top: 27px;right: 0;z-index: 999;">
                    <el-input size="small" v-model="templateNameSearch" style="width:150px;" placeholder="请输入搜索信息"></el-input>
                    <el-button type="primary" size="small" @click="getComplaintTemplate"> 搜索 </el-button>
                </div>
                <el-tabs style="margin-top: 5px;" v-model="chiefModelName" @tab-click="handleModelClick">
                    <el-tab-pane label="公用模板" name="0">
                    </el-tab-pane>
                    <el-tab-pane label="个人模板" name="1">
                    </el-tab-pane>
                    <el-table class="l-table" :data="complaintTemplateList" border max-height="300" highlight-current-row>
                        <el-table-column prop="templateName" label="模板名称">
                            <template slot-scope="scope">
                                <span>{{scope.row.templateName || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="templateDetails" label="模板详情">
                            <template slot-scope="scope">
                                <span>{{scope.row.templateDetails || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <span class="table-btn-size" @click="quoteModel(scope.row)">引用模板</span>
                                <span v-if="chiefModelName != '0'" class="table-btn-size" @click="editModel(scope.row)">编辑模板</span>
                                <span v-if="chiefModelName != '0'" class="table-btn-size table-btn-del" @click="delectModel(scope.row)">删除</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tabs>
            </div>
            <div slot="footer" class="dialog-btn">
                <el-button size="small" @click="closeDialog('chiefComplaintDialog')">取 消</el-button>
                <el-button type="primary" size="small" @click="saveChiefComplaint">保 存</el-button>
            </div>
        </el-dialog>


        <!-- ------------------ 主诉/现病史/既往史模板 ------------------ -->
        <el-dialog class="dialog-frame dialog-second" style="" width="400" :visible.sync="chiefModelDialog" @close="closeDialog('chiefModelDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form class="proposal-form" :model="chiefModelForm" :rules="chiefModelFormRule" ref="chiefModelForm" label-position="left" label-width="80px">
                <el-form-item label="模板类型" prop="templateType" width="100%">
                    <el-select v-model="chiefModelForm.templateType" style="width:100%" placeholder="模板类型">
                        <el-option value="1" label="主诉"></el-option>
                        <el-option value="2" label="现病史"></el-option>
                        <el-option value="3" label="既往史"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="模板名称" prop="templateName">
                    <el-input type="text" v-model="chiefModelForm.templateName" style="width:100%" auto-complete="off" placeholder="模板名称" size="middle"></el-input>
                </el-form-item>
                <el-form-item prop="templateDetails" label="模板内容" width="100%">
                    <el-input type="textarea" placeholder="请输入内容" style="width:100%;resize:none;" v-model="chiefModelForm.templateDetails" maxlength="500"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-btn">
                <el-button size="small" @click="closeDialog('chiefModelDialog')">取 消</el-button>
                <el-button type="primary" size="small" @click="addChiefForm('chiefModelForm')">确 定</el-button>
            </div>
        </el-dialog>


        <!-- ------------------ 结束问诊 ------------------ -->
        <el-dialog class="dialog-frame dialog-finish" :visible.sync="finishDataDialog" @close="closeDialog('finishDataDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>结束问诊</span>
            </div>
            <div class="finish-frame" v-loading="finishLoading" element-loading-text="" element-loading-background="rgba(255,255,255,.7)">
                <p class="finish-tips">结束问诊前，请让患者确认以下内容：</p>
                <el-form class="x-form s-sm" ref="finishForm" :data="finishForm" label-width="40%" size="small">
                    <el-form-item label="是否线下支付：" prop="payWay">
                        <el-radio-group v-model="finishForm.payWay">
                            <el-radio label="offline">是</el-radio>
                            <el-radio label="online">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="finishForm.payWay == 'offline'" label="配送方式：" prop="deliveryMode">
                        <el-radio-group v-model="finishForm.deliveryMode">
                            <el-radio :label="2">自提</el-radio>
                            <el-radio :label="1">配送</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>

                <div class="finish-btn">
                    <el-button type="primary" class="btn-size" @click="handleFinishDialog(1)">成功问诊</el-button>
                    <el-button type="primary" plain class="btn-size" @click="handleFinishDialog(0)">未成功问诊</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- ------------------ 开中/西药处方 ------------------ -->
        <drug-dialog ref="drugDialog" is-sub @closed="closeDialog('westernMedicineDialog')"></drug-dialog>


        <!-- ------------------ 诊断 ------------------ -->
        <diagnosis-dialog ref="diagnosisDialogComponent" is-sub @closed="val => closeDialogComponent(val,'diagnosisDialogComponent')"></diagnosis-dialog>


        <!-- ------------------ 修改患者资料弹框 ------------------ -->
        <update-patient-dialog ref="updatePatient" is-sub @submited="data => onSubmitDialog('updatePatient', data)"></update-patient-dialog>

        <!-- ------------------ 患者二维码 ------------------ -->
        <patient-code-dialog ref="patientCodeDialog" @closed="init"></patient-code-dialog>


        <!-- 编辑付费类型 -->
        <the-dialog :cfg="paymentCfg" :loading="paymentLoading" :need-close-modal="false" @closed="closeDialog('payment')" @submited="submitPaymentForm">
            <template slot="body">
                <el-form class="x-form" ref="paymentForm" :model="paymentForm" :rules="paymentRules" :disabled="paymentLoading" size="small" label-width="120px">
                    <el-form-item label="付费类型" prop="paymentMethod">
                        <el-select class="o-select--full" v-model="paymentForm.paymentMethod" placeholder="请选择付费类型">
                            <el-option v-for="(o,idx) in $dict.paymentMethodIds" :key="idx" :label="o.name" :value="o.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </template>
        </the-dialog>

        <!-- 医保：修改病种 -->
        <update-disease ref="updateDisease" @submited="onSubmitDialog('updateDisease')"></update-disease>

        <!-- 查看病历组件 -->
        <case-history ref="caseHistory"></case-history>
    </section>
</template>

<script>
    import DiagnosisDialog from './components/DiagnosisDialog';
    import DrugDialog from '@/components/chatroom/drug-dialog';
    import UpdatePatientDialog from './components/UpdatePatientInfoDialog';
    import PatientCodeDialog from '@/components/patient-qr-dialog';
    import UpdateDisease from './components/DiseaseDialog';
    import caseHistory from '@/components/case-history';
    import pdfDialog from '@/components/chatroom/view-pdf';

    export default {
        components: {
            'diagnosis-dialog': DiagnosisDialog,
            'drug-dialog': DrugDialog,
            'update-patient-dialog': UpdatePatientDialog,
            PatientCodeDialog,
            UpdateDisease,
            caseHistory,
            pdfDialog
        },
        data() {
            return {
                logId: sessionStorage.autoLogId || '', // 问诊id
                patientId: sessionStorage.autoPatientId || '', // 患者id

                patientInfo: {}, // 患者资料
                patientInfoField: [
                    { prop: 'patientName', label: '姓名' },
                    { slot: 'patientSex', label: '性别' },
                    { prop: 'patientBirthday', label: '生日' },
                    { slot: 'patientWeight', label: '身高/体重(kg)' },
                    { prop: 'patientProfession', label: '职业' },
                    { slot: 'isMarried', label: '婚否' },
                    { prop: 'patientPhone', label: '手机号码' },
                    { prop: 'patientIdcard', label: '身份证' },
                    { prop: 'patientMaritalStatus', label: '籍贯' },
                    { slot: 'autonomousAddress', label: '住址' },
                    { slot: 'isDrugAllergy', label: '药物过敏史' },
                    { slot: 'paymentMethod', label: '付费类型' },
                    { prop: 'hospitalEntityName', label: '医疗机构' },
                    { prop: 'departmentName', label: '医疗科室' },
                    { slot: 'mainSuit', label: '主诉', column: 1 },
                    { slot: 'presentIllness', label: '现病史', column: 1 },
                    { slot: 'historyPresentIllness', label: '既往史', column: 1 },
                    { slot: 'diagnosisArray', label: '诊断', column: 1 },
                    { slot: 'prescriptionList', label: '电子处方', column: 1 },
                ],


                /* --------- 主诉/现病史/既往史 --------- */
                chiefComplaintDialog: false, //主诉、现病史、既往史弹框
                chiefModelDialog: false, //主诉、现病史、既往史新增模板弹框
                chiefDialog: {
                    chiefInput: '',
                    nowInput: '',
                    pastInput: '',
                },
                chiefModelForm: { //新增主诉、现病史、既往史模板
                    templateType: '',
                    templateName: '',
                    templateDetails: '',
                },
                chiefModelFormRule: { //新增主诉、现病史、既往史模板
                    templateType: [{ required: true, message: '模板类型不能为空', trigger: 'change' }],
                    templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
                    templateDetails: [{ required: true, message: '模板内容不能为空', trigger: 'blur' }],
                },
                chiefComplaintName: '1', //主诉、现病史、既往史--tab
                chiefModelName: '0', //主诉、现病史、既往史--公用和个人模板
                complaintTemplateList: [], //主诉、现病史、既往史--公用和个人模板--列表
                templateNameSearch: '', //主诉、现病史、既往史--公用和个人模板--搜索
                modelId: null, //编辑模板的id


                /* --------- 过敏史 --------- */
                allergyHistoryDialog: false, //过敏史弹框
                isAllergy: '2', //是否有过敏史
                isAllergyInput: '', //有过敏史的输入框
                allergyLoading: false, //过敏史加载


                /* --------- 诊断 --------- */
                diagnosisDialog: false, //诊断弹框
                addCustomICDDialog: false, //自定义诊断弹框


                /* --------- 开处方 --------- */
                chineseMedicineDialog: false, //中药弹框
                prescriptionInfoListDialog: false, //西药--历史处方--查看详情
                addPrescriptionDialog: false, //西药--开药弹框
                addPrescriptionTemplateDialog: false, //西药--另存模板弹框
                chineseDrugTipsDialog: false, //生成中药特殊提示弹框
                drugUsageList: {}, //获取药品用法列表
                drugFrequencyList: {}, //获取药品频次列表
                isWesternChinese: '', //中药还是西药(1中药 2西药 不传则查全部)



                /* --------- 问诊结束 --------- */
                finishDataDialog: false, //结束问诊弹框
                finishLoading: false,
                finishForm: {
                    patientName: '', // 患者姓名（ 1 - 成功问诊时必传）
                    deliveryMode: '', // 配送方式 1 - 物流配送， 2 - 自提（ 1 - 成功问诊时必传）
                    autonomousAddress: '', // 地址（ 自主开方）（ 1 - 成功问诊时必传）
                    payWay: '', // offline - 为线下支付， online - 为线上支付（ 1 - 成功问诊时必传）
                    phoneNumber: '', // 患者手机号 （1-成功问诊时必传）
                    addressCity: '',
                },


                /* ------------------ 历史处方模块 ------------------ */
                historySearch: '',
                historyList: [],

                /* --- 付费类型弹框 --- */
                paymentLoading: false,
                paymentForm: {
                    paymentMethod: ''
                },
                paymentRules: {
                    paymentMethods: [{ required: true, message: '请选择付费类型', trigger: 'change' }]
                },
                paymentCfg: {
                    visible: false,
                    title: '编辑付费类型'
                },

            }
        },
        mounted() {
            this.init();
        },
        methods: {
            init() {
                this.$ajax.getLastInquiryByAuto().then(res => {
                    if (res.data && res.data.logId) {
                        // 获取上次未结束的问诊
                        this.logId = sessionStorage.autoLogId = res.data.logId;
                        this.patientId = sessionStorage.autoPatientId = res.data.patientId;

                        this.getPatientInfo();
                    } else {
                        // 不存在未结束的问诊，初始化数据
                        sessionStorage.autoLogId && sessionStorage.removeItem('autoLogId');
                        sessionStorage.autoPatientId && sessionStorage.removeItem('autoPatientId');
                        Object.assign(this.$data, this.$options.data.call(this));
                    }
                }).catch(err => {
                    this.$util.message(err.msg);
                })

                this.getHistoryList();
            },
            // 播放音频
            tipMusicBtn() {
                let audio = document.getElementById("dingding");
                audio.play();
            },
            //获取患者信息
            getPatientInfo() {
                if (!this.logId) return false;

                let para = {
                    id: this.logId
                }

                sessionStorage.autoLogId = this.logId;
                sessionStorage.autoPatientId = this.patientId;

                this.$ajax.getAllInfo(para).then(res => {
                    this.patientInfo = res.data || {};

                    // 是否有过敏史
                    this.isAllergy = this.patientInfo.isDrugAllergy || '2';

                }).catch(err => {
                    this.$util.message(err.msg)
                })
            },
            onShowDialog(type) {
                switch (type) {
                    case 'updatePatient': // 修改患者资料弹框
                        if (this.patientId) {
                            this.$refs.updatePatient && this.$refs.updatePatient.onOpen(this.patientId, this.patientInfo)
                        } else {
                            this.$refs.updatePatient && this.$refs.updatePatient.onOpen()
                        }

                        break;
                }
            },
            onSubmitDialog(type, data = {}) {
                if (type == 'updatePatient') {
                    this.logId = data.logId;
                    this.patientId = data.patientId;
                }

                this.getPatientInfo();

            },
            //打开弹框
            openDialog(dialogName, templateType) {
                if (!this.logId) {
                    this.$util.message('请先填写就诊人信息')
                    return false;
                }

                if (dialogName == 'finishDataDialog') { //结束问诊
                    this.finishDataDialog = true;
                    this.finishLoading = false;

                    this.finishForm.patientName = this.patientInfo.patientName;
                    this.finishForm.phoneNumber = this.patientInfo.phoneNumber;
                    this.finishForm.autonomousAddress = this.patientInfo.autonomousAddress;
                    this.finishForm.addressCity = this.patientInfo.addressCity;

                    this.finishForm.deliveryMode = 1;
                    this.finishForm.payWay = 'online';
                }

                if (dialogName == 'caseHistory') { // 查询病历
                    this.$nextTick(() => {
                        if (this.$global.platform('lj')) {
                            this.$refs.caseHistory.onOpen('his', this.patientInfo)
                        } else {
                            if (this.$global.isNewCase) {
                                this.$refs.caseHistory.onOpen('ca', {
                                    ...this.patientInfo,
                                    id: this.logId
                                });
                            } else {
                                this.$refs.caseHistory.onOpen('normal', {
                                    caseInfo: this.patientInfo,
                                    idCard: this.patientInfo.patientIdcard
                                });
                            }
                        }
                    })
                }

                if (dialogName == 'payment') { // 付费方式
                    this.paymentCfg.visible = true;
                    this.paymentLoading = false;
                    this.paymentForm.paymentMethod = this.patientInfo.paymentMethod || '';
                    this.$refs.paymentDialog && this.$refs.paymentDialog.clearValidate();
                }

                if (dialogName == 'disease') { // 病种
                    this.$refs.updateDisease && this.$refs.updateDisease.onOpen(this.patientInfo)
                }

                if (dialogName == 'chiefComplaintDialog') { //主诉、现病史、既往史弹框
                    this.chiefComplaintDialog = true;
                    this.chiefComplaintName = templateType;

                    this.chiefDialog.chiefInput = this.patientInfo.mainSuit || '';
                    this.chiefDialog.nowInput = this.patientInfo.presentIllness || '';
                    this.chiefDialog.pastInput = this.patientInfo.historyPresentIllness || '';

                    this.chiefModelName = '0';
                    this.getComplaintTemplate();
                    if (this.patientInfo.mainSuit != '' && templateType == '1') {
                        this.chiefDialog.chiefInput = this.patientInfo.mainSuit
                    }
                    if (this.patientInfo.presentIllness != '' && templateType == '2') {
                        this.chiefDialog.nowInput = this.patientInfo.presentIllness
                    }
                    if (this.patientInfo.historyPresentIllness != '' && templateType == '3') {
                        this.chiefDialog.pastInput = this.patientInfo.historyPresentIllness
                    }
                }

                if (dialogName == 'chiefModelDialog') { //主诉、现病史、既往史新增模板弹框
                    this.chiefModelDialog = true;
                    this.chiefModelForm.templateType = '1';
                    this.chiefModelForm.templateName = '';
                    this.chiefModelForm.templateDetails = '';
                    this.modelId = null;
                }

                if (dialogName == 'allergyHistoryDialog') { //过敏史弹框
                    this.allergyHistoryDialog = true;
                    this.isAllergy = this.patientInfo.patientAllergyDetails ? '1' : '2';
                    this.isAllergyInput = this.patientInfo.patientAllergyDetails || '';
                }


                /*** 需填写主诉+诊断的操作 ***/
                if (['westernMedicineDialog', 'chineseMedicineDialog'].includes(dialogName)) {
                    if (!this.patientInfo.mainSuit || !this.patientInfo.diagnosis) {
                        this.$util.message('请先填写主诉和诊断', 'warning')

                        return false;
                    }

                    // 中、西药弹框
                    if (dialogName == 'westernMedicineDialog' || dialogName == 'chineseMedicineDialog') {
                        /*** 中西药弹框 start ***/
                        let drugType = ''
                        if (dialogName == 'westernMedicineDialog') {
                            drugType = '2'
                        } else {
                            drugType = '1'
                        }
                        let data = {
                            logId: this.logId,
                            diagnosisArray: this.patientInfo.diagnosisArray,
                            drugType,
                            inquiryPatientId: this.patientId
                        }
                        this.$refs.drugDialog.onOpen({
                            data,
                            isEdit: false,
                            paymentMethod: this.patientInfo.paymentMethod
                        })
                    }
                }
            },
            //关闭弹框
            closeDialog(dialogName) {
                if (dialogName == 'westernMedicineDialog') { //西药弹框
                    this.westernMedicineDialog = false;
                    this.isWesternChinese = '';
                    this.getPatientInfo();
                } else if (dialogName == 'chiefModelDialog') { //主诉、现病史、既往史新增模板弹框
                    this.chiefModelDialog = false;
                    this.$nextTick(() => {
                        this.$refs.chiefModelForm.resetFields();
                    })
                } else if (dialogName == 'addPrescriptionDialog') { //处方历史--开药弹框
                    this.addPrescriptionDialog = false;
                    if (this.isWesternChinese == 2) {
                        this.$nextTick(() => {
                            this.$refs.drugClassForm.resetFields();
                        })
                    } else {
                        this.$nextTick(() => {
                            this.$refs.drugChineseForm.resetFields();
                        })
                    }

                } else if (dialogName == 'payment') {
                    this.paymentCfg.visible = false;
                } else {
                    this[dialogName] = false;
                }
            },


            /* ------------------ 主诉/现病史/既往史 ------------------ */
            handleChiefClick(tab, event) { //主诉、现病史、既往史tab
                this.chiefComplaintName = tab.name;
                this.chiefModelName = '0';
                this.getComplaintTemplate();

                // if (this.patientInfo.mainSuit != '') {
                //     this.chiefDialog.chiefInput = this.patientInfo.mainSuit
                // } 
                // if (this.patientInfo.presentIllness != '') {
                //     this.chiefDialog.nowInput =  this.patientInfo.presentIllness
                // } 
                // if (this.patientInfo.historyPresentIllness != '') {
                //     this.chiefDialog.pastInput = this.patientInfo.historyPresentIllness
                // } 
            },
            handleModelClick(tab, event) { //获取主诉、现病史、既往史---个人模板、公用模板tab
                this.chiefModelName = tab.name;
                this.getComplaintTemplate();
            },
            getComplaintTemplate() { //获取主诉、现病史、既往史模板
                let para = {
                    isPersonalTemplate: this.chiefModelName,
                    templateType: this.chiefComplaintName,
                }

                if (this.templateNameSearch != '') { para.templateName = this.templateNameSearch }
                this.$ajax.getTemplate(para).then(res => {
                    this.complaintTemplateList = res.data.list || []
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            quoteModel(row) { //引用模板
                if (row.templateType == '1') {
                    this.chiefDialog.chiefInput = row.templateDetails
                } else if (row.templateType == '2') {
                    this.chiefDialog.nowInput = row.templateDetails
                } else if (row.templateType == '3') {
                    this.chiefDialog.pastInput = row.templateDetails
                }
            },
            editModel(row) { //编辑模板
                this.chiefModelDialog = true;
                this.modelId = row.id;
                this.chiefModelForm.templateType = row.templateType;
                this.chiefModelForm.templateName = row.templateName;
                this.chiefModelForm.templateDetails = row.templateDetails;
            },
            delectModel(row) { //删除模板
                this.$confirm(`是否确认删除个人模板？`, '删除', {
                    customClass: 'l-confirm',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                    this.$ajax.deleteTemplate({ id: row.id }).then(res => {
                        this.getComplaintTemplate();
                        this.$message({
                            message: res.msg,
                            type: 'success',
                        })
                    }).catch(err => {
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                }).catch(() => {})
            },
            saveChiefComplaint() { //保存主诉、现病史、既往史
                let para = {
                    webToken: this.$authInfo.webToken(),
                    id: this.logId,
                }
                para.mainSuit = this.chiefDialog.chiefInput
                para.presentIllness = this.chiefDialog.nowInput
                para.historyPresentIllness = this.chiefDialog.pastInput
                this.$ajax.updateInquiryLog(para).then(res => {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                    })
                    this.chiefComplaintDialog = false;
                    this.getPatientInfo();
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            clearChief() { //清空主诉、现病史、既往史
                this.$confirm(`是否确认清空？`, '清空', {
                    customClass: 'l-confirm',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                    if (this.chiefComplaintName == '1') {
                        this.chiefDialog.chiefInput = ''
                    } else if (this.chiefComplaintName == '2') {
                        this.chiefDialog.nowInput = ''
                    } else {
                        this.chiefDialog.pastInput = ''
                    }
                }).catch(() => {})
            },
            addChiefForm(formName) { //主诉、现病史、既往史新模板--新增&编辑
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let para = {
                            webToken: this.$authInfo.webToken(),
                        }
                        for (let key in this.chiefModelForm) {
                            para[key] = this.chiefModelForm[key]
                        }
                        if (this.modelId) { para.id = this.modelId }
                        this.$ajax.newTemplate(para).then(res => {
                            this.$message({
                                message: res.msg,
                                type: 'success',
                            })
                            this.chiefModelDialog = false;
                            this.$nextTick(() => {
                                this.$refs[formName].resetFields();
                            })
                            this.getComplaintTemplate();
                        }).catch(err => {
                            this.$message({
                                message: err.msg,
                                type: 'error',
                            })
                        })
                    } else {

                    }
                })
            },



            /* ------------------ 过敏史 ------------------ */
            updateAllergyHistory() { //过敏史--保存
                this.allergyLoading = true;
                let para = {
                    webToken: this.$authInfo.webToken(),
                    patientAllergyDetails: this.isAllergy == '1' ? this.isAllergyInput : '',
                    id: this.patientId,
                }
                this.$ajax.updateAllergyHistory(para).then(res => {
                    this.allergyHistoryDialog = false;
                    this.allergyLoading = false;
                    this.isAllergyInput = '';
                    this.$message({
                        message: res.msg,
                        type: 'success',
                    })
                    this.getPatientInfo();
                }).catch(err => {
                    this.allergyLoading = false;
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },


            /* ------------------ 诊断 ------------------ */
            openDiagnosisDialog(data = []) {
                if (this.logId && this.logId != null) {
                    this.$nextTick(() => {
                        this.$refs.diagnosisDialogComponent.onOpen({
                            logId: this.logId,
                            data
                        })
                    })
                } else {
                    this.$message.closeAll();
                    this.$message({
                        message: '请先填写就诊人信息',
                        type: 'error',
                    })
                }
            },
            closeDialogComponent(flag, refName) {
                if (flag) {
                    this.getPatientInfo();
                }

            },


            /* ------------------ 结束问诊 ------------------ */
            handleFinishDialog(type) {
                if (type === 0) {
                    this.$confirm(`是否结束当前开方？`, '温馨提示', {
                        customClass: 'l-confirm',
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(() => {
                        this.endInquiry(type)
                    }).catch(() => {})
                } else {
                    if (!this.patientInfo.prescriptionList || this.patientInfo.prescriptionList.length < 1) {
                        this.$util.message('请开具电子处方')
                        return false;
                    }

                    this.endInquiry(type)
                }
            },
            endInquiry(type) { //结束问诊
                this.finishLoading = true;

                let params = {
                    id: this.logId,
                    isSuccess: type
                }

                if (type === 1) {
                    // 成功问诊
                    for (let k in this.finishForm) {
                        if ([].includes(k)) {
                            continue;
                        } else if (k == 'deliveryMode') {
                            if (this.finishForm.payWay == 'online') {
                                continue;
                            } else {
                                params[k] = this.finishForm[k]
                            }
                        } else {
                            params[k] = this.finishForm[k]
                        }
                    }
                };

                this.$ajax.endInquiryByAuto(params).then(res => {
                    this.$util.message(res.msg, 'success');
                    this.finishDataDialog = false;
                    this.finishLoading = false;
                    sessionStorage.autoLogId = '';
                    sessionStorage.autoPatientId = '';

                    if (type == 1 && params.payWay == 'online') {
                        this.showQrDialog(res.data);
                    } else {
                        this.init();
                    }
                }).catch(err => {
                    this.finishLoading = false;
                    this.$util.message(err.msg)
                    tempWindow && tempWindow.close();
                })

            },
            showQrDialog(data) {
                this.$refs.patientCodeDialog && this.$refs.patientCodeDialog.onOpen({ data });
            },


            /* ------------------ 查看PDF+保存图片 ------------------ */
            getEstablishPdf(id, resourceType) { //打开pdf、img
                let params = {
                    id: id, //数据id 
                    resource: resourceType, //1=生成住院建议书 2=生成健康指导 3=生成检验检查单 4=生成处方单
                }

                this.$refs.pdfDialog && this.$refs.pdfDialog.onOpen(params);
            },

            /* ------------------ 历史处方模块 ------------------ */
            // 搜索处方
            getHistoryList() {
                let params = {};

                if (this.historySearch) params.searchKeywords = this.historySearch;

                this.$ajax.getHistoryListByAuto(params).then(res => {
                    this.historyList = res.data.list || [];
                }).catch(err => {
                    this.$util.message(err.msg);
                })
            },


            /* ------------------ 付费类型 ------------------ */
            submitPaymentForm() { // 提交付费类型修改
                this.paymentLoading = true;

                this.$refs.paymentForm.validate(valid => {
                    if (valid) {
                        let params = {
                            logId: this.logId,
                            paymentMethod: this.paymentForm.paymentMethod
                        }

                        this.$ajax.updatePaymentMethodByZh(params).then(res => {
                            this.paymentLoading = false;
                            this.paymentCfg.visible = false;

                            this.$util.message(res.msg, 'success')
                            this.getPatientInfo();
                        }).catch(err => {
                            this.paymentLoading = false;
                            this.$util.message(err.msg)
                        })


                    } else {
                        this.paymentLoading = false;
                    }
                })
            },
        },
    }
</script>

<style lang="scss" src="@/style/page/vedio.scss"></style>
<style lang="scss" src="@/style/page/chat.scss"></style>